package com.myrent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.myrent.entity.User;
import com.myrent.mapper.UserMapper;
import com.myrent.service.UserService;
import com.myrent.shiro.CustomizedToken;
import com.myrent.shiro.LoginType;
import com.myrent.utils.SaltUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public Boolean login(String phoneNum, String password) {
        Subject currentUser = SecurityUtils.getSubject();
        boolean b = currentUser.isAuthenticated();
        CustomizedToken token = new CustomizedToken(phoneNum, password, LoginType.USER.toString());
        token.setRememberMe(false);
        try {
            currentUser.login(token);
        } catch (AuthenticationException e) {
            log.error("登录验证失败", e);
            return false;
        }
        return true;
    }

    @Override
    public User getUserByPhoneNum(String phoneNum) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone_num", phoneNum);
        return getOne(wrapper);
    }

    @Override
    public void register(User user) {
        String password = user.getPassword();
        String salt = SaltUtil.produceSalt();
        ByteSource byteSource = ByteSource.Util.bytes(salt);
        SimpleHash simpleHash = new SimpleHash("md5", password, byteSource, SaltUtil.getEncryptNum());
        user.setPassword(simpleHash.toHex());
        user.setRole(null);
        user.setSalt(salt);
        userMapper.insert(user);
    }


}

